package com.fyzk.activity.user.xiangxi;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.chongzhi.RechargeActivity;
import com.fyzk.activity.user.jczq_sp.JCZQ_SPActivity;
import com.fyzk.bean.AccountMoneyResponse;
import com.fyzk.bean.NumOrderInfo;
import com.fyzk.betcode.AppLotteryCodeListManager;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.dialog.DJ_ProgressDialog;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.net.PublicMethod;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

/**
 * 数字彩 投注详情
 */

//@ContentView(R.layout.orderdetail)
@ContentView(R.layout.order_num_lottery_detail)
public class NumLotteryOrderDetailActivity extends BaseActivity {

    protected String id;

    private TopTitleView xiangxi_title_rl;
    private TextView tv_caiZhong;
    private TextView tv_money;
    private TextView tv_couponMoney;
    private LinearLayout ll_couponMoney;
    private TextView tv_beiShu;
    private TextView tv_id;
    private TextView tv_phase;
    private TextView tv_time;
    private TextView tv_state;
    private TextView xiangxi_tiket  ;
    private TextView tv_prizeMoney;
    @ViewInject(R.id.xiangxi_jczqsp_tv)
    private TextView xiangxi_jczqsp_tv;
    @ViewInject(R.id.wincode_title)
    private LinearLayout wincode_title;

    protected LinearLayout ll_content;
    protected LinearLayout ll_prize;

    private TextView tv_jiXu;
    private TextView tv_jiXu_bet;
    protected TextView jczq_sp_tv;
    @ViewInject(R.id.xiangxi_bettype)
    private TextView xiangxi_bettype;
    @ViewInject(R.id.iv_plan_detail)
    private RelativeLayout ivDetail;
    @ViewInject(R.id.iv_plan_content)
    private RelativeLayout ivContent;
    @ViewInject(R.id.iv_icon)
    private ImageView ivIcon;
    @ViewInject(R.id.tv_zhushu)
    private TextView zhushu;
    @ViewInject(R.id.ll_plan_detail)
    protected LinearLayout ll_detail;

    private double leftMoney;   // 用户彩金
    private int orderMoney;     // 订单彩金(整数，用int)
    private long lowMoney;       // 待支付差额(支付必须是整数)
    private boolean detailIsShow = true;
    private boolean contentIsShow = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        info();
        id = getIntent().getStringExtra(IntentParamUtils.BETDETAILID);
        DJ_ProgressDialog.show(getContext(), true, true);
        getOrderInfo();
        requestLeftMoney();
    }

    private void requestLeftMoney() {
        httpPostJson(CommandUtil.ACCOUNT_MONEY, Commands.ACCOUNT_MONEY, null, true);
    }


    protected void getOrderInfo() {
        JSONObject json = new JSONObject();
        try {
            json.put("orderid", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpPostJson(CommandUtil.COMMON_BET_RECORD_DETAIL, Commands.ORDERINFO, json, true);

    }

    private void continueBet() {
        JSONObject json = new JSONObject();
        try {
            json.put("orderid", id);
            json.put("lotteryType", info.getLotteryType());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpPostJson(CommandUtil.REBET, Commands.REBET, json, true);

    }

    NumOrderInfo info;

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.ACCOUNT_MONEY:
                AccountMoneyResponse accountMoneyResponse = JSON.parseObject(resultBean.getData(),
                        AccountMoneyResponse.class);
                leftMoney = Double.parseDouble(PublicMethod.formatBalance(accountMoneyResponse.getBalance()));
                break;
            case CommandUtil.COMMON_BET_RECORD_DETAIL:
                perseOrder(resultBean);
                fuZhi();

                break;
            case CommandUtil.REBET:
                try {
                    JSONObject object = new JSONObject(resultBean.getData());
                    if (object.has("orderid")) {
                        id = object.getString("orderid");
                        new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("订单已受理")
                                .setNegativeButton("确定", new DialogInterface
                                        .OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                        getOrderInfo();
                                    }
                                }).setCancelable(false).create().show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }


    /**
     * 得到内容串
     *
     * @return
     */
    public String getContent() {
            return "";
    }

    /**
     * 得到开奖号码
     *
     * @return
     */
    public String getPrize() {
            return "";
    }

    public String getLotteryId() {
            return info.getLotteryType()+"";
    }

    /**
     * 初始化控件
     */
    private void info() {

        xiangxi_title_rl = (TopTitleView) findViewById(R.id.order_topview);
        xiangxi_title_rl.setOnTitleClickListener(this);

        tv_caiZhong = (TextView) findViewById(R.id.order_lotteryName);
        tv_money = (TextView) findViewById(R.id.xiangxi_fanganmoney);
        tv_couponMoney = (TextView) findViewById(R.id.xiangxi_couponmoney);
//        ll_couponMoney = (LinearLayout) findViewById(R.id.xiangxi_coupon_ll);
        tv_beiShu = (TextView) findViewById(R.id.xiangxi_beishu);
        tv_id = (TextView) findViewById(R.id.xiangxi_fanganid);
//        tv_phase = (TextView) findViewById(R.id.xiangxi_phase);
        tv_time = (TextView) findViewById(R.id.xiangxi_time);
        tv_state = (TextView) findViewById(R.id.xiangxi_state);
        tv_prizeMoney = (TextView) findViewById(R.id.xiangxi_zjmoney);
        xiangxi_tiket = (TextView) findViewById(R.id.xiangxi_tiket);

        ll_content = (LinearLayout) findViewById(R.id.xiangxi_content);
        ll_prize = (LinearLayout) findViewById(R.id.xiangxi_ll_prizeinfor);


        tv_jiXu = (TextView) findViewById(R.id.order_txt_continue);
        tv_jiXu_bet = (TextView) findViewById(R.id.order_txt_continue2);
        tv_jiXu_bet.setVisibility(View.GONE);

        jczq_sp_tv = (TextView) findViewById(R.id.xiangxi_jczqsp_tv);
        jczq_sp_tv.setOnClickListener(new ZCXX_onClick());

        tv_jiXu.setOnClickListener(new ZCXX_onClick());
        tv_jiXu_bet.setOnClickListener(new ZCXX_onClick());

    }

    /**
     * 给控件赋值
     */
    public void fuZhi() {
        if (!TextUtil.isEmpty(info.getIsRecharge()) && info.getIsRecharge().equals("1")) {
            xiangxi_title_rl.setRightVisible(View.VISIBLE);
            xiangxi_title_rl.setRightTxt("支付");
        } else {
            xiangxi_title_rl.setRightVisible(View.INVISIBLE);
        }
        orderMoney = info.getAmount() / 100;
        tv_caiZhong.setText(info.getLotteryTypeName()+"  第"+ info.getPhase() + "期");
        tv_money.setText("付款彩金："+PublicMethod.formatMoney(info.getAmount())+"米");
//        if (info.getPreferentialAmount() > 0) {
//            tv_couponMoney.setText(""+PublicMethod.formatMoney(info.getPreferentialAmount()));
//        } else {
//            ll_couponMoney.setVisibility(View.GONE);
//        }
        tv_beiShu.setText("倍数" + info.getMultiple() + "倍");
        tv_id.setText("" +id);
//        tv_phase.setText("" );
        tv_time.setText("" + info.getReceiveTime());
        tv_state.setText("" + info.getOrderResultStatusName());
        xiangxi_tiket.setText("" + info.getOrderStatusName());

        if (info.getAddprize() > 0){
            tv_prizeMoney.setText(Html.fromHtml(String.valueOf(
                    PublicMethod.formatMoney(info.getPrize()*1.0))+"<font color='#666666'>(加奖</font>"
                    +PublicMethod.formatMoney(info.getAddprize() * 1.0)+"<font color='#666666'>)</font>米"));
        }else {
            tv_prizeMoney.setText(String.valueOf(
                    PublicMethod.formatMoney(info.getPrize()*1.0))+"米");
        }

        if(!TextUtil.isEmpty(info.getWincode())){
            xiangxi_jczqsp_tv.setVisibility(View.VISIBLE);
            wincode_title.setVisibility(View.VISIBLE);
            xiangxi_jczqsp_tv.setText(info.getWincode());
        }
        ll_content.removeAllViews();
        if (addContent() != null) {
            ll_content.addView(addContent());
        }
//        ll_prize.removeAllViews();
//        if (addPrize() != null) {
//            ll_prize.addView(addPrize());
//        }
        xiangxi_bettype.setText(info.getBettype());
        zhushu.setText(info.getBetnum() + "注");

//        if (responseObj != null && (responseObj.lotteryType.equals("" + LotteryIDUtils
//                .JLSF_LOTTERY_ID_INT) ||
//                responseObj.lotteryType.equals("" + LotteryIDUtils.JLRSF_LOTTERY_ID_INT) ||
//                responseObj.lotteryType.equals("" + LotteryIDUtils.JLSFC_LOTTERY_ID_INT) ||
//                responseObj.lotteryType.equals("" + LotteryIDUtils.JLDXF_LOTTERY_ID_INT) ||
//                responseObj.lotteryType.equals("" + LotteryIDUtils.JLHH_LOTTERY_ID_INT) ||
//                responseObj.lotteryType.equals("" + LotteryIDUtils.JLHH_LOTTERY_ID_INT))) {
//            jczq_sp_tv.setVisibility(View.GONE);
//        }
        ivIcon.setImageResource(AppLotteryInfos.getLogoId(info.getLotteryType()));
        ivContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (contentIsShow){
                    contentIsShow = false;
                    ll_content.setVisibility(View.GONE);
                }else {
                    contentIsShow = true;
                    ll_content.setVisibility(View.VISIBLE);
                }
            }
        });
        ivDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (detailIsShow){
                    detailIsShow = false;
                    ll_detail.setVisibility(View.GONE);
                }else {
                    detailIsShow = true;
                    ll_detail.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    /**
     * 拆分投注内容
     */
    private void splitContent(String content) {
        if (content == null || content.equals("")) {
            return;
        }
        String front = "";
        if (content.contains("-")) {
            front = content.split("-")[0];
        }

//        if (front != null && front.length() >= 9) {
//            wanFaId = front.substring(0, 4);
//            wanFa = front.substring(4, 5);
//            guoGuan = front.substring(5, front.length());
//        } else {
//            wanFaId = front;
//        }
    }


    /**
     * 单击事件
     *
     * @author Administrator
     */
    class ZCXX_onClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
//                case R.id.xiangxi_title_iv_back:
//                    finish();
//                    break;
                case R.id.order_txt_continue:
                    if (AppLotteryCodeListManager.betType == AppLotteryCodeListManager.OKTOBACK) {
                        finish();
                        return;
                    }
                    if (ContinueBuy.jiXu(getContext(), getLotteryId())) {
                        finish();
                    }
                    break;
                case R.id.order_txt_continue2:
                    if (info != null) {
                        continueBet();
                    } else {
                        AppToast.getToast().show("本单信息不全，请重新获取");
                    }
                    break;
                case R.id.xiangxi_jczqsp_tv:
                    Intent intent = new Intent(NumLotteryOrderDetailActivity.this, JCZQ_SPActivity.class);
                    intent.putExtra(IntentParamUtils.BETDETAILID, id);
                    startActivity(intent);
                    break;
                default:
                    break;
            }

        }

    }


    protected void perseOrder(StringResultBean resultBean) {
        info = JSON.parseObject(resultBean.getData(),NumOrderInfo.class);
    }

    private String betCode = "";
    protected View addContent() {

//		RaceBaseView view = RaceFactory.getRaceView(info.getLotteryType());
////		view.codeFilter =Integer.parseInt(info.codeFilter);
//		return view.getRaceView(getContext(), getContent(),null, info.getWincode());

        LinearLayout layout_all = new LinearLayout(this);
        layout_all.setOrientation(LinearLayout.VERTICAL);
        for (NumOrderInfo.DetailBean bean : ((NumOrderInfo)info).getDetail()) {
            if (betCode.equals("")) {
                betCode = bean.getBetcode();
            }
            LinearLayout layout = new LinearLayout(this);
            layout.setOrientation(LinearLayout.VERTICAL);
            TextView wf = new TextView(this);
            wf.setTextColor(getResources().getColor(R.color.textcolor_black));
            wf.setText("玩法："+bean.getPlayName());
            layout.addView(wf);
            TextView code = new TextView(this);
            code.setTextColor(getResources().getColor(R.color.textcolor_black));
            code.setText(bean.getBetcode());
            layout.addView(code);
            layout_all.addView(layout);
        }

        return  layout_all;

    }


    protected View addPrize() {

        return null;
    }

    @Override
    public void onRightClick() {
        lowMoney = orderMoney - (int)leftMoney;
        Intent intent = new Intent(getContext(), RechargeActivity.class);
        intent.putExtra(IntentParamUtils.ORDER_ID, id);
        intent.putExtra(IntentParamUtils.lowMoney, lowMoney);
        startActivityForResult(intent, IntentParamUtils.LOWMONEY_TO_RECHARGE_OK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntentParamUtils.LOWMONEY_TO_RECHARGE_OK) {  // 支付完返回 刷新订单
            getOrderInfo();
        }
    }

}
